# -*- coding: utf-8 -*-
"""
-------------------------------------------------
   File Name：     conf
   Description :
   Author :       Jolg
   date：          2021/11/4
-------------------------------------------------
   Change Activity:
                   2021/11/4:
-------------------------------------------------
"""

import json

from fastapi import APIRouter,Body,Depends
import sys
from conf import config
import hashlib
import time
import jwt
from fastapi import Header, HTTPException,Request
from conf import logger,db
import uuid
from utils.tool import Dict2Obj
from utils.resp import *


router = APIRouter()
SECRET_KEY=config.SECRET_KEY
def md5value(s):
    md5 = hashlib.md5()
    md5.update(s)
    return md5.hexdigest()

@router.post("/login/",summary='获取TOKEN')
async def login(username: str=Body(...), password: str=Body(...),):
    logger.info((username,password))
    pass5=md5value(password.encode())
    logger.info([username,pass5])
    sql1 = '''select t.*  from fsuser t where t.username=%s and t.password=%s'''
    user = db.queryobj(sql1, (username,pass5))
    logger.info(user)
    if user:
        info = {"userid": user[0].id, 'username': user[0].username,'nicename':user[0].nicename}
        payload = {
            "iat": int(time.time()),
            "exp": int(time.time()) + 86400 * 7,
            # token签发者
            'iss': 'zlWang',
            'data': info,
            "jti": "4f1g23a12aa"
        }
        # 生成token
        # token = str(jwt.encode(payload, SECRET_KEY, algorithm='HS512', ), 'utf-8')
        token = jwt.encode(payload, SECRET_KEY, algorithm='HS512', )
        # logger.info(token)
        data = {"token": token, "userinfo": info}
        return success(data)
    else:
        return fail()


class User_info:
    def __init__(self,userid):
        self.USERID=userid
    def myspace(self):
        sql = '''select t.quota from USERPFILE t where t.userid=:userid'''
        sp = db.dictpesql(sql, {'userid':self.USERID})
        if sp:
            return sp[0]['QUOTA']
        else:
            return config.PERQUOTA

    def usespace(self):
        sql = '''select nvl(sum(t.fsize),0) smsize from USERFILE t where t.userid=:userid'''
        ufsz = db.dictpesql(sql, {'userid':self.USERID})
        if ufsz:
            return ufsz[0]['SMSIZE']
        else:
            return 0

class Check_user:
    def __init__(self,request: Request ,TOKEN: str = Header(None)):
        if str(request.url).endswith('/user/login/'):
            return
        elif TOKEN:
            tk=TOKEN
            users = ''
            try:
                users = jwt.decode(tk, SECRET_KEY, algorithms=['HS512'])
            except Exception as e:
                logger.error(e)
            if not users:
                data = {"msg": "用户未登录!", "code": -1}
                raise HTTPException(status_code=200, detail=data)
            else:
                if config.ACCESS_RECORDS:
                    sql = '''insert into access_records(id,userid,username,nicename,accessmethod,accessurl,accessdate)
                            values(%s,%s,%s,%s,%s,%s,current_time)'''
                    # logger.info(users['data'])
                    user = Dict2Obj(users['data'])
                    logger.info(user)
                    db.duexe(sql,(uuid.uuid1(),user.userid,user.username,user.nicename,str(request.method),str(request.url)))
                    self.USERID=user.userid
                    self.USERNAME=user.username
                    self.NICENAME=user.nicename
        else:
            data = {"msg": "用户未登录!", "code": -1}
            raise HTTPException(status_code=200, detail=data)

@router.get("/userList",summary='用户列表')
async def userList(user :Check_user= Depends(Check_user)):
    sql1 = '''select t.*  from fsuser t '''
    menu = db.querydict(sql1,())
    logger.info(menu)
    data = {"msg": "",  "code": 1, "menu": menu}
    return data

@router.put("/userList",summary='新增用户')
async def addUser(user :Check_user= Depends(Check_user)):
    sql1 = '''select t.*  from menus t '''
    menu = db.querydict(sql1,())
    logger.info(menu)
    data = {"msg": "",  "code": 1, "menu": menu}
    return data


@router.post("/userList",summary='修改用户')
async def editUser(user :Check_user= Depends(Check_user)):
    sql1 = '''select t.*  from menus t '''
    menu = db.querydict(sql1,())
    logger.info(menu)
    data = { "menu": menu}
    return success(data)

@router.delete("/userList",summary='删除用户')
async def delUser(user :Check_user= Depends(Check_user)):
    sql1 = '''select t.*  from menus t '''
    menu = db.querydict(sql1,())
    logger.info(menu)
    data = {"menu": menu}
    return success(data)

@router.get("/groupList",summary='用户组列表')
async def getGroupList(user :Check_user= Depends(Check_user)):
    sql1 = '''select t.*  from usergroup t '''
    menu = db.querydict(sql1,())
    logger.info(menu)
    data = { "menu": menu}
    return success(data)

@router.put("/groupList",summary='新增用户组')
async def getGroupList(groupname:str=Body(...), user :Check_user= Depends(Check_user)):
    checksql='select * from usergroup g where g.groupname=%s '
    group=db.queryobj(checksql,(groupname))
    if len(group)>0:
        return fail({},"用户组已存在")
    else:
        sql1 = '''insert into usergroup values(%s,%s,current_time) '''
        db.duexe(sql1,(uuid.uuid1(),groupname))
    return success()
@router.delete("/groupList",summary='删除用户组')
async def getGroupList(user :Check_user= Depends(Check_user)):
    sql1 = '''select t.*  from menus t '''
    menu = db.querydict(sql1,())
    logger.info(menu)
    data = {"menu": menu}
    return success(data)

@router.post("/groupList",summary='修改用户组')
async def editGroup(user :Check_user= Depends(Check_user)):
    sql1 = '''select t.*  from menus t '''
    menu = db.querydict(sql1,())
    logger.info(menu)
    data = { "menu": menu}
    return success(data)

@router.put("/menuToGroup",summary='用户组添加菜单')
async def addMenuToGroup(user :Check_user= Depends(Check_user)):
    sql1 = '''select t.*  from menus t '''
    menu = db.querydict(sql1,())
    logger.info(menu)
    data = {"menu": menu}
    return success(data)

@router.delete("/MenuInGroup",summary='用户组取消菜单')
async def CancleMenuForGroup(user :Check_user= Depends(Check_user)):
    sql1 = '''select t.*  from menus t '''
    menu = db.querydict(sql1,())
    logger.info(menu)
    data = {"menu": menu}
    return success(data)